package com.caigou.modules.forum.ui.packet

import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.PacketDetailItemAdapter
import com.caigou.modules.forum.bean.PacketDetailBean
import com.caigou.modules.forum.bean.PacketRecordBean
import com.caigou.modules.forum.databinding.ActivityPacketDetailBinding
import com.caigou.modules.forum.viewmodel.PacketViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2022/02/21
 */
@Route(path = RouterPath.Forum.PAGE_PACKET)
@AndroidEntryPoint
class PacketDetailActivity : BaseActivity() {

    private lateinit var binding: ActivityPacketDetailBinding
    private val packetViewModel: PacketViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.RED_PACKET_ID)
    var redPacketId = 0

    private var page = 1
    private val limit = 10
    private var totalPage = 0

    private val mAdapter: PacketDetailItemAdapter by lazy {
        PacketDetailItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPacketDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.packetDetailLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.packetDetailSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchPacketDetail()
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchPacketRecordList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.packetDetailRecyclerView.run {
            layoutManager = LinearLayoutManager(this@PacketDetailActivity)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@PacketDetailActivity))
        }

        binding.packetDetailTvBack.setOnClickListener {
            finish()
        }

        fetchPacketDetail()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(packetViewModel.packetDetailLiveData, ::handleGetPacketDetail)
        observe(packetViewModel.packetRecordListLiveData, ::handleGetPacketRecordList)
    }

    private fun handleGetPacketDetail(result: Resource<PacketDetailBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.packetDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取红包记录异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.packetDetailSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                handleUI(result.data!!)
                fetchPacketRecordList()
            }
        }
    }

    private fun handleGetPacketRecordList(result: Resource<PacketRecordBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.packetDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取红包记录异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.packetDetailSwipeRefreshLayout.isRefreshing = false

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleUI(bean: PacketDetailBean) {
        if (TextUtils.isEmpty(bean.receiverHeadImg)) {
            binding.packetDetailIvAvatar.setImageResource(R.drawable.img_comm_avatar)
        } else {
            ImageLoader.loadCircle(this, bean.receiverHeadImg, binding.packetDetailIvAvatar)
        }
        binding.packetDetailTvNickname.text = "${bean.senderNickName}的红包"
        binding.packetDetailTvMoney.text = bean.amount.toString()

        binding.packetDetailTvDesc.text =
            "已领取${bean.usedNum}/${bean.redPacketNum}，共${bean.totalAmount}元"
    }

    private fun fetchPacketDetail() {
        packetViewModel.getPacketDetail(redPacketId, AppBackgroundInfo.instance.userBean!!.userId)
    }

    private fun fetchPacketRecordList() {
        packetViewModel.getPacketRecordList(1, 10, redPacketId)
    }
}